package com.example.sbbbbb;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;
import com.google.android.material.textfield.TextInputEditText;

public class MainActivity extends AppCompatActivity {

    // 声明UI组件
    private TextInputEditText etUsername, etPassword;
    private Button btnLogin;
    private TextView tvWelcome;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // 保留原有的EdgeToEdge配置
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_main);

        // 初始化窗口插入处理
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });

        // 初始化登录组件
        initViews();
        setupLoginButton();
    }

    private void initViews() {
        etUsername = findViewById(R.id.et_username);
        etPassword = findViewById(R.id.et_password);
        btnLogin = findViewById(R.id.btn_login);
        tvWelcome = findViewById(R.id.tv_welcome);
    }

    private void setupLoginButton() {
        btnLogin.setOnClickListener(v -> {
            if (validateInput()) {
                handleSuccessfulLogin();
            }
        });
    }

    private boolean validateInput() {
        String username = etUsername.getText().toString().trim();
        String password = etPassword.getText().toString().trim();

        boolean isValid = true;

        if (username.isEmpty()) {
            etUsername.setError("请输入账号");
            isValid = false;
        } else if (username.length() < 6) {
            etUsername.setError("账号至少6位字符");
            isValid = false;
        }

        if (password.isEmpty()) {
            etPassword.setError("请输入密码");
            isValid = false;
        } else if (password.length() < 8) {
            etPassword.setError("密码至少8位字符");
            isValid = false;
        }

        return isValid;
    }

    private void handleSuccessfulLogin() {
        // 显示欢迎信息
        tvWelcome.setText("欢迎，" + etUsername.getText().toString());
        tvWelcome.setVisibility(View.VISIBLE);

        // 隐藏登录表单
        hideLoginForm();

        // TODO: 在这里添加跳转到主界面的逻辑
        // startActivity(new Intent(this, HomeActivity.class));
    }

    private void hideLoginForm() {
        findViewById(R.id.iv_logo).setVisibility(View.GONE);
        findViewById(R.id.til_username).setVisibility(View.GONE);
        findViewById(R.id.til_password).setVisibility(View.GONE);
        btnLogin.setVisibility(View.GONE);
    }
}